package com.codeyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeyang.domain.Menu;
import com.codeyang.dto.MenuDto;
import com.codeyang.mapper.MenuMapper;
import com.codeyang.mapper.RoleMenuMapper;
import com.codeyang.service.MenuService;
import com.codeyang.vo.DataGridView;
import com.codeyang.vo.MenuTreeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: TO-删除标志-DO
 *
 * @author CodeYang_Site
 * @version 2021/4/20 15:34
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public DataGridView lisPage(MenuDto menuDto) {
        Page<Menu> page = new Page<>(menuDto.getPageNum(), menuDto.getPageSize());
        page.addOrder(OrderItem.desc(Menu.COL_UPDATE_TIME));
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(menuDto.getMenuName()), Menu.COL_MENU_NAME, menuDto.getMenuName());
        qw.eq(StringUtils.isNotBlank(menuDto.getStatus()), Menu.COL_STATUS, menuDto.getStatus());

        menuMapper.selectPage(page, qw);
        return new DataGridView(page.getTotal(), page.getRecords());

    }

    @Override
    public boolean saveMenu(MenuDto menuDto) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuDto, menu);
        // data person
        menu.setCreateTime(new Date());
        menu.setCreateBy(menuDto.getSimpleUser().getUserName());
        menu.setUpdateTime(menu.getCreateTime());
        return menuMapper.insert(menu) > 0;
    }

    @Override
    public boolean updateMenu(MenuDto menuDto) {
        return false;
    }


    /**
     * 使用角色iud 查询菜单的ids
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Long> getMenuIdsByRoleId(Long roleId) {
//        /**
//         * 查询中间表
//         */
//        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
//
//        // sql 是 select role_id,menu_id form sys_role_menu where  role_id =
//        // 优化 这里不需要 角色id
//        // select menu_id from sys_role_menu where role_id =
//        // mp 的操作方式
//        qw.select(RoleMenu.COL_MENU_ID);
//        qw.eq(RoleMenu.COL_ROLE_ID, roleId);
//        List<RoleMenu> roleMenus = roleMenuMapper.selectList(qw);
//        if (CollectionUtils.isEmpty(roleMenus)) {
//            return Collections.emptyList();
//        }
//        //收集数据
//        List<Long> collect = roleMenus.parallelStream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Long> menuIds = roleMenuMapper.getMenuIdsByRoleId(roleId);
        return menuIds;
    }





    @Override
    public List<MenuTreeVo> getMenuByUserId(Long userId, boolean isAdmin) {
        // 1 管理员拥有所有的菜单
        List<Menu> menus = null;
        if (isAdmin) {
            QueryWrapper<Menu> qw = new QueryWrapper<>();
            qw.in(Menu.COL_MENU_TYPE, "M", "C");
            menus = list(qw);
        } else {
            // 2 不是管理员: 使用用户的id--> 角色的id--> 查询菜单的id---> 菜单
            /**
             * SELECT
             * 	m.menu_id,
             * 	m.parent_id,
             * 	m.parent_ids,
             * 	m.menu_name,
             * 	m.menu_type,
             * 	m.percode,
             * 	m.`path`,
             * 	m.remark,
             * 	m.`status`,
             * 	m.create_time,
             * 	m.update_time,
             * 	m.create_by,
             * 	m.update_by
             * FROM
             * 	sys_menu AS m
             * 	LEFT JOIN sys_role_menu AS rm ON rm.menu_id = m.menu_id
             * 	LEFT JOIN sys_role_user AS ru ON ru.role_id = rm.role_id
             * WHERE
             * 	ru.user_id = 12
             */
            menus = menuMapper.getMenuByUserId(userId);
        }
        if (!CollectionUtils.isEmpty(menus)) {
            List<MenuTreeVo> menuTreeVos = menus.parallelStream().
                    map(
                            menu -> new MenuTreeVo(menu.getMenuId() + "", menu.getPath())
                    ).collect(Collectors.toList());
            return menuTreeVos;

        }
        return Collections.emptyList();
    }

    @Override
    public List<String> getUsePermissions(Long userId, boolean isAdmin) {
        // 如果是管理使用mp
        if (isAdmin) {
            QueryWrapper<Menu> qw = new QueryWrapper<>();
            qw.eq(Menu.COL_MENU_TYPE, "F");
            List<Menu> list = list(qw);
            if (CollectionUtils.isEmpty(list)) {
                return Collections.emptyList();
            }
            return list.parallelStream().map(Menu::getPercode).collect(Collectors.toList());
        }
        return menuMapper.getUsePermissions(userId);
    }
}
